//这里是自定义方法，服务端可根据需求重新覆盖此函数。
//方法内的代码是根据你们提供的main.js挑出来的，请检查是否有遗漏。

var customFunction = function(){
  //前端开发注：这里validate_result返回可能有问题。
  //validate_result是在ajax请求成功后得到结果，而下面的return可能未等请求成功就已经返回，
  //故validate_result永远是初始的false
  //建议使用jQueryValidator的remote解决这个问题，验证规则不用smscode，而是用remote。
  //参考：http://jqueryvalidation.org/remote-method/

  //添加自定义验证规则，短信验证码
  $.validator.addMethod('smscode', function (value, element, params) {
    //var smscode = /^[0-9]{6}$/;
    if ($("#bind_phone").val()) {
      var phone = $("#bind_phone").val();
    }
    else {
      var phone = $("#phone").val();
    }
    var data = {};

    data.recipient = phone;
    data.captcha = value;
    var validate_result = false;
    $.ajax({
        async: false,
        dataType: "json",
        url: window.apis.validateSMScode,
        data: data,
        success: function (json) {
            validate_result = json.result;
        },
    });
    return this.optional(element) || validate_result;
  });
  //添加自定义验证规则，密码
  $.validator.addMethod('passwordcode', function (value, element, params) {
    var username = $("#username").val();
    var data = {};

    data.username = username;
    data.password = value;
    var validate_result = false;
    $.ajax({
        async: false,
        dataType: "json",
        url: window.apis.validatePassword,
        data: data,
        success: function (json) {
            validate_result = json.result;
        },
    });
    return this.optional(element) || validate_result;
  });
  //添加自定义验证规则，商城发送短信验证码
  $.validator.addMethod('sccode', function (value, element, params) {
    var captcha_encrypt = $("#id_captcha_0").val();
    var data = {};

    data.captcha = value;
    data.captcha_encrypt = captcha_encrypt;
    var validate_result = false;
    $.ajax({
        async: false,
        dataType: "json",
        url: window.apis.validateStoreCaptchacode,
        data: data,
        success: function (json) {
            validate_result = json.result;
        },
    });
    return this.optional(element) || validate_result;
  });
  // ?
  $("[data-toggle='join-us']").on('click', function(){
      var cont = $("#join-us");
      var cont_content = cont.find('.modal-content');
      cont_content.find('.position-name').html($(this).attr('data-name'));
      cont_content.find('.position-department').html($(this).attr('data-department'));
      cont_content.find('.position-num').html($(this).attr('data-num'));
      cont_content.find('.position-responsibilities').html($(this).attr('data-responsibilities'));
      cont_content.find('.position-requirements').html($(this).attr('data-requirements'));
      cont.modal()
  })
}

var initSMS = function () {
  var maxTime = 60;
  var nowTime = maxTime;
  var timer;
  var phonenum = /^[0-9]{11}$/;
  //发送验证短信
  $('#sendCodeBtn').on("click", function () {
    var that = $(this);
    var type = $(this).data("type");
    if (type == 'email'){
      var email = $('#email').val();
    } else {
      if ($("#bind_phone").val()) {
        var phone = $("#bind_phone").val();
      } else {
        var phone = $("#phone").val();
      }
    };


    var params = {};

    //如果表单里有手机号码输入框，但用户未填写手机号码，则弹窗并中止
    if (phone && !phonenum.test(phone)) {
      alert("无效的手机号码");
      return;
    }

    if (phone) {
      params.phone = phone;
    }
    if (email) {
      params.email = email;
      maxTime = 120;
    }

    that.attr("disabled", "true");


    $.ajax({
      dataType: "json",
      url: window.apis.smscode + '?r=' + Math.random(),
      data: params,
      success: function (json) {
        //        console.log("code send done!");
        // alert('DEBUG,短信发送成功,SMSCode:' + json.data.msmCode);
      },
      error: function (error) {
        alert('DEBUG,短信发送失败');
        console.log(error);
      }
    });

    timer = setInterval(function () {
      if (nowTime > 0) {
        nowTime--;
        that.children("span").text(' (' + nowTime + ')');
      } else {
        that.removeAttr("disabled");
        that.html("重新发送<span></span>");
        clearInterval(timer);
        nowTime = maxTime;
      }
    }, 1000);
  });

}

function addMoveFav(element){
    var that = element;
    //点击收藏或移除
    var params = {
      product_id: that.parent().data("pid")
    };
    var isAddlove = element.hasClass("addlove");
    var api = isAddlove ? window.apis.addlove : window.apis.removelove;
    var msg = isAddlove ? "已收藏！" : "已取消收藏！";
    //向接口发送请求
    $.getJSON(api + "?r=" + Math.random(), params, function (data) {
      if (data.status){
        that.hide().siblings("a").show();
        alert(msg)
      } else {
        alert(data.message)
      }
    });
    return false;
  };

function removeMyLoves(element) {
    var that = element;
    var p = that.closest("li");
    var pid = p.data("pid");
    var params = {
      product_id: pid
    };
    // p.remove();
    $.getJSON(window.apis.removelove + "?r=" + Math.random(), params, function (data) {
      if (data.status){
        alert("成功移除！")
        p.remove()
      } else {
        alert(data.message)
      }
    });
}

function getCookie(name) {
    var cookieValue = null;
    if (document.cookie && document.cookie != '') {
        var cookies = document.cookie.split(';');
        for (var i = 0; i < cookies.length; i++) {
            var cookie = jQuery.trim(cookies[i]);
            // Does this cookie string begin with the name we want?
            if (cookie.substring(0, name.length + 1) == (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}

